package vn.ivs.taxiapp.fragments;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.w3c.dom.Document;

import vn.ivs.taxiapp.GMapV2Direction;
import vn.ivs.taxiapp.R;
import vn.ivs.taxiapp.S001Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.graphics.Color;
import android.location.Address;
import android.location.Geocoder;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.EditText;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.PolylineOptions;

public class S003Fragment extends Fragment implements OnClickListener {

	// Controls
	private EditText etSourcePoint, etDesPoint;
	private Button btnSource, btnDes, btnSearch;
	// private LinearLayout llSlider;
	private ProgressDialog mDialog;

	// Variables
	private boolean isSourceClicked = false;
	private boolean isDesClicked = false;
	private String addSource = null;
	private String addDes = null;

	// For google map
	private GMapV2Direction mapDirection = new GMapV2Direction();
	private LatLng latlngSource;
	private LatLng latlngDes;

	// Animation
	Animation mAniRight, mAniLeft, mAniMoveLeft, mAniMoveRight, mAniFadeIn,
			mAniFadeOut;

	// Google Map
	public static GoogleMap googleMap;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View v = inflater.inflate(R.layout.fragment_s003, container, false);

		// For controls declaration
		// llSlider = (LinearLayout) findViewById(R.id.llSlideView);
		etSourcePoint = (EditText) v.findViewById(R.id.etSourcePoint);
		etDesPoint = (EditText) v.findViewById(R.id.etDesPoint);
		btnSource = (Button) v.findViewById(R.id.btnSource);
		btnSearch = (Button) v.findViewById(R.id.btnSearch);
		btnDes = (Button) v.findViewById(R.id.btnDes);

		// load the animation
		mAniRight = AnimationUtils.loadAnimation(getActivity()
				.getApplicationContext(), R.anim.slide_right);
		mAniLeft = AnimationUtils.loadAnimation(getActivity()
				.getApplicationContext(), R.anim.slide_left);
		mAniMoveLeft = AnimationUtils.loadAnimation(getActivity()
				.getApplicationContext(), R.anim.move_left);
		mAniMoveRight = AnimationUtils.loadAnimation(getActivity()
				.getApplicationContext(), R.anim.move_right);
		mAniFadeIn = AnimationUtils.loadAnimation(getActivity()
				.getApplicationContext(), R.anim.fade_in);
		mAniFadeOut = AnimationUtils.loadAnimation(getActivity()
				.getApplicationContext(), R.anim.fade_out);
		btnSource.setOnClickListener(this);

		btnDes.setOnClickListener(this);

		btnSearch.setOnClickListener(this);

		setUpMapIfNeeded(); // For setting up the MapFragment
		return v;
	}

	/***** Sets up the map if it is possible to do so *****/
	public static void setUpMapIfNeeded() {
		// Do a null check to confirm that we have not already instantiated the
		// map.
		if (googleMap == null) {
			// Try to obtain the map from the SupportMapFragment.
			googleMap = ((SupportMapFragment) S001Activity.fragmentManager
					.findFragmentById(R.id.map)).getMap();
			// Check if we were successful in obtaining the map.
			if (googleMap != null)
				setUpMap();
		}
	}

	/**
	 * This is where we can add markers or lines, add listeners or move the
	 * camera.
	 * <p>
	 * This should only be called once and when we are sure that
	 * {@link #googleMap} is not null.
	 */
	public static void setUpMap() {
		// Moving camera
		CameraPosition cameraPosition = new CameraPosition.Builder()
				.target(new LatLng(10.82310, 106.62966)).zoom(12).build();

		googleMap.animateCamera(CameraUpdateFactory
				.newCameraPosition(cameraPosition));

		// create marker
		// MarkerOptions marker = new MarkerOptions().position(
		// new LatLng(latBitexco, lngBitexco)).title("B蘯｡n ﾄ疎ng 盻�ﾄ妥｢y");

		// Changing marker icon
		// marker.icon(BitmapDescriptorFactory
		// .fromResource(R.drawable.ic_marker));

		// adding marker
		// googleMap.addMarker(marker);

		// Set type
		googleMap
				.setMapType(GoogleMap.MAP_TYPE_NORMAL);
		// googleMap.setMapType(googleMap.MAP_TYPE_HYBRID);
		// googleMap.setMapType(googleMap.MAP_TYPE_SATELLITE);
		// googleMap.setMapType(googleMap.MAP_TYPE_TERRAIN);
		// googleMap.setMapType(googleMap.MAP_TYPE_NONE);

		// Show current location
		googleMap.setMyLocationEnabled(false); // false to disable

		// Show zoom button
		googleMap.getUiSettings().setZoomControlsEnabled(true); // true
																				// to
		// enable
	}

	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		if (googleMap != null)
			setUpMap();

		if (googleMap == null) {
			// Try to obtain the map from the SupportMapFragment.
			googleMap = ((SupportMapFragment) S001Activity.fragmentManager
					.findFragmentById(R.id.map)).getMap();
			// Check if we were successful in obtaining the map.
			if (googleMap != null)
				setUpMap();
		}
	}

	/****
	 * The mapfragment's id must be removed from the FragmentManager or else if
	 * the same it is passed on the next time then app will crash
	 ****/
	@Override
	public void onDestroyView() {
		reloadMap();
		super.onDestroyView();
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btnSource:
			if (isSourceClicked == false) {
				etSourcePoint.setVisibility(View.VISIBLE);
				etSourcePoint.startAnimation(mAniRight);
				etSourcePoint.startAnimation(mAniFadeIn);
				isSourceClicked = true;
			} else {
				etSourcePoint.setVisibility(View.GONE);
				etSourcePoint.startAnimation(mAniLeft);
				etSourcePoint.startAnimation(mAniFadeOut);
				isSourceClicked = false;
			}
			break;

		case R.id.btnDes:
			if (isDesClicked == false) {
				etDesPoint.setVisibility(View.VISIBLE);
				etDesPoint.startAnimation(mAniRight);
				etDesPoint.startAnimation(mAniFadeIn);
				isDesClicked = true;
			} else {
				etDesPoint.setVisibility(View.GONE);
				etDesPoint.startAnimation(mAniLeft);
				etDesPoint.startAnimation(mAniFadeOut);
				isDesClicked = false;
			}
			break;

		case R.id.btnSearch:
			// get address from 2 edittexts
			addSource = etSourcePoint.getText().toString().trim();
			addDes = etDesPoint.getText().toString().trim();

			latlngSource = getPlaceLocation("Ben Thanh market, Ho Chi Minh");
			latlngDes = getPlaceLocation("Bitexco tower, Ho Chi Minh");
			// Test direction
			AsyncTask<Void, Void, Document> as = new AsyncTask<Void, Void, Document>() {

				@Override
				protected void onPreExecute() {
					mDialog = new ProgressDialog(getActivity());
					mDialog.show();
					super.onPreExecute();
				}

				@Override
				protected Document doInBackground(Void... params) {

					Document doc = mapDirection.getDocument(latlngSource,
							latlngDes, GMapV2Direction.MODE_DRIVING);
					return doc;
				}

				@Override
				protected void onPostExecute(Document result) {
					mDialog.dismiss();

					// Make maker for 2 points
					// create marker
					MarkerOptions markerSource = new MarkerOptions().position(
							latlngSource).title("B蘯｡n ﾄ疎ng 盻�ﾄ妥｢y");

					// Changing marker icon
					markerSource.icon(BitmapDescriptorFactory
							.fromResource(R.drawable.ic_marker));

					// adding marker
					googleMap.addMarker(markerSource);

					// create marker
					MarkerOptions markerDes = new MarkerOptions().position(
							latlngDes).title("B蘯｡n ﾄ訴 ﾄ黛ｺｿn ﾄ妥｢y");

					// Changing marker icon
					markerDes.icon(BitmapDescriptorFactory
							.fromResource(R.drawable.ic_marker2));

					// adding marker
					googleMap.addMarker(markerDes);

					CameraPosition cameraPosition = new CameraPosition.Builder()
							.target(latlngSource).zoom(16).build();

					googleMap.animateCamera(CameraUpdateFactory
							.newCameraPosition(cameraPosition));

					// Draw direction
					ArrayList<LatLng> directionPoint = mapDirection
							.getDirection(result);
					PolylineOptions rectLine = new PolylineOptions().width(20)
							.color(Color.RED);

					for (int i = 0; i < directionPoint.size(); i++) {
						rectLine.add(directionPoint.get(i));
					}

					googleMap.addPolyline(rectLine);

					AlertDialog.Builder builder = new AlertDialog.Builder(
							getActivity());
					builder.setTitle("Distance");
					builder.setMessage(mapDirection.getDistanceText(result));
					builder.setPositiveButton("OK", null);
					builder.create();
					builder.show();

				}
			};
			as.execute();
			break;

		default:
			break;
		}

	}

	private LatLng getPlaceLocation(String address) {
		List<Address> listAddress = null;
		LatLng latlngInfo = null;
		double lat = 0.0, lng = 0.0;
		Geocoder geoCoder = new Geocoder(getActivity().getApplicationContext());
		try {
			listAddress = geoCoder.getFromLocationName(address, 1);
			lat = listAddress.get(0).getLatitude();
			lng = listAddress.get(0).getLongitude();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		latlngInfo = new LatLng(lat, lng);

		return latlngInfo;
	}

	public void reloadMap() {
		SupportMapFragment f = (SupportMapFragment) getFragmentManager()
				.findFragmentById(R.id.map);
		if (f != null) {
			try {
				getFragmentManager().beginTransaction().remove(f).commit();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		googleMap = null;
	}

}
